package com.gzdh.dishrecognition.ui.fragment.report;

import android.content.Context;
import android.hardware.display.DisplayManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.StringUtils;
import com.dhkj.web.utils.MyObserverRes;
import com.dhkj.web.utils.RequestUtils;
import com.gzdh.dishrecognition.R;
import com.gzdh.dishrecognition.config.SysConstConfig;
import com.gzdh.dishrecognition.emu.OfflineGetCardSnTypeEmus;
import com.gzdh.dishrecognition.model.LcReportDto;
import com.gzdh.dishrecognition.ui.activity.ReportActivity;
import com.gzdh.dishrecognition.ui.adapter.report.LcReportAdapter;
import com.gzdh.dishrecognition.ui.dialog.MsgDialog;
import com.gzdh.dishrecognition.ui.listnenr.FragmentKeyEventListener;
import com.gzdh.dishrecognition.ui.pre.LcReportPre;
import com.gzdh.dishrecognition.util.ByteUtil;
import com.gzdh.dishrecognition.util.ScanKeyManager;
import com.gzdh.dishrecognition.util.SystemUtils;
import com.jiebao.nfc.uartnfc.CardReaderDevice;
import com.serialport.JBScanner;
import com.serialport.OnDecodeCallback;

import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.disposables.Disposable;

public class LcReportFragment extends Fragment implements FragmentKeyEventListener {

    private Context mContext;

    private ReportActivity activity;

    //副屏
    public Display mDisplay;
    //主屏
    public Display mMainDisplay;

    private LcReportPre lcReportPre;
    private RelativeLayout msgRv;
    private LinearLayout linearLayout;
    private TextView dateTopTv;
    private LinearLayout dateMsgLinear;
    private RecyclerView recyclerView;
    private LcReportAdapter lcReportAdapter;

    private JBScanner scanner = null;

    public LcReportFragment(ReportActivity activity) {
        this.activity = activity;
    }

    private ScanKeyManager scanKeyManager;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View view = inflater.inflate(R.layout.fragment_report_lc, container, false);
        mContext = view.getContext();
        msgRv = view.findViewById(R.id.msgRv);
        linearLayout = view.findViewById(R.id.dateLinear);
        dateTopTv = view.findViewById(R.id.dateTopTv);
        dateMsgLinear = view.findViewById(R.id.dateMsgLinear);
        recyclerView = view.findViewById(R.id.recyclerView);
        getDisplays();
        return view;
    }

    Disposable mdDisposable;

    @Override
    public void onResume() {
        super.onResume();
        if (mDisplay != null) {
            lcReportPre = new LcReportPre(activity, mDisplay);
            lcReportPre.show();
        }

        switch (SysConstConfig.getInstance().getPeripheralDeviceModel()) {
            case defaultType:
                CardReaderDevice.getInstance().initCardReader();
                scanner = new JBScanner(callback);
                scanner.startScan();

                mdDisposable = Flowable.intervalRange(0, 60, 0, 1, TimeUnit.SECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .doOnNext((aLong -> {


                            String cardNo = CardReaderDevice.getInstance().readCardNo();
                            if (!StringUtils.isEmpty(cardNo)) {
                                onCard(cardNo);
                            }

                        }))
                        .doOnComplete(() -> {
                            System.out.println("定时器时间到");
                        })
                        .subscribe();
                break;
            case cloudQrAndReadCard:
                System.out.println("云设备");
                scanKeyManager = new ScanKeyManager((String value) -> {
                    Log.i("MainActivity", "ScanValue->" + value);
                    if (value.length() < 10) {
                        onCard(value);
                    } else {
                        getDatas(value);
                    }
                });
                break;
        }
        lcReportAdapter = new LcReportAdapter(activity);
        LinearLayoutManager layoutManager = new LinearLayoutManager(activity);
        recyclerView.setLayoutManager(layoutManager);
        activity.setFragmentKeyEventListener(this);
    }


    private OnDecodeCallback callback = new OnDecodeCallback() {
        @Override
        public void onDecode(final String code) {
            Log.e("TAG", "onDecode_ = " + code + " code length " + code.length());
            String codeTrim = code.trim();
            Log.e("TAG", "codeTrim = " + codeTrim + " code length " + codeTrim.length());
            if (code.length() < 10) {
                onCard(code);
            } else {
                getDatas(code);
            }
        }
    };

    @Override
    public void onPause() {
        super.onPause();
        if (lcReportPre != null) {
            lcReportPre.dismiss();
        }
        activity.setFragmentKeyEventListener(null);
        CardReaderDevice.getInstance().deInitCardReader();

        if (scanner != null) {
            scanner.stopScan();
            scanner = null;
        }
    }

    public void getDisplays() {

        DisplayManager displayManager = (DisplayManager) activity.getSystemService(Context.DISPLAY_SERVICE);
        Display[] presentationDisplays = displayManager.getDisplays();
        mMainDisplay = presentationDisplays[0];
        if (presentationDisplays.length > 1) {
            mDisplay = presentationDisplays[1];
        } else
            mDisplay = null;
    }

    @Override
    public boolean onFragmentKeyEvent(KeyEvent keyEvent) {
        if (keyEvent.getKeyCode() != KeyEvent.KEYCODE_BACK) {
            if(scanKeyManager != null) {
                scanKeyManager.analysisKeyEvent(keyEvent);
                return true;
            }
        }
        return false;
    }

    public void onCard(String auth) {
        if(SysConstConfig.getInstance().getOfflineGetCardSnType() == OfflineGetCardSnTypeEmus.reverse) {
            byte[] cardSnTemp = ByteUtil.hexStringToByte(auth.toUpperCase());
            byte[] cardSn = new byte[4];
            for (int i = 0; i < cardSnTemp.length; i++) {
                cardSn[i] = cardSnTemp[3 - i];
            }
            auth = ByteUtil.bytesToHexString(cardSn).toUpperCase();
        }
        if (mdDisposable != null && !mdDisposable.isDisposed()) {
            mdDisposable.dispose();
            mdDisposable = null;
        }
        getDatas(auth);

    }

    private void getDatas(String auth) {
        RequestUtils.getLcReport(mContext, SystemUtils.getSerialNumber(), auth, new MyObserverRes<JSONObject>(mContext, false) {
            @Override
            public void onSuccess(JSONObject result) {
                System.out.println(result.toJSONString());
                msgRv.setVisibility(View.GONE);
                linearLayout.setVisibility(View.VISIBLE);
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append("当前餐次：" + result.getJSONObject("bmcm").getString("name"));
                stringBuffer.append(" CardNo:" + result.getJSONObject("fk").getString("cardno"));
                stringBuffer.append("  姓名：" + result.getJSONObject("fk").getString("name"));
                stringBuffer.append("  卡余额：" + result.getJSONObject("fk").getString("kye"));
                stringBuffer.append("  补贴金额：" + result.getJSONObject("fk").getString("btye"));
                dateTopTv.setText(stringBuffer.toString());

                List<LcReportDto> list = result.getJSONArray("lcData").toJavaList(LcReportDto.class);
                if (list.size() == 0) {
                    recyclerView.setVisibility(View.GONE);
                    dateMsgLinear.setVisibility(View.VISIBLE);
                    return;
                } else {
                    recyclerView.setVisibility(View.VISIBLE);
                    dateMsgLinear.setVisibility(View.GONE);
                }
                recyclerView.setAdapter(lcReportAdapter);
                lcReportAdapter.setLcReportDtoList(list);
                if (lcReportPre != null) {
                    lcReportPre.showSuccess(result);
                }
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                System.out.println("errorMsg:" + errorMsg);
                msgRv.setVisibility(View.VISIBLE);
                linearLayout.setVisibility(View.GONE);
                if(!activity.isFinishing()){
                    MsgDialog msgDialog = new MsgDialog(activity);
                    msgDialog.show();
                    TextView msg = msgDialog.getMsgTv();
                    msg.setText(errorMsg);
                    msg.setTextSize(30);
                }
                if (lcReportPre != null) {
                    lcReportPre.showError(errorMsg);
                }

            }
        });
    }

}
